Option Strict On
Imports System
Imports DevExpress.CodeRush.StructuralParser
Imports DX_Contrib
Imports SP = DevExpress.CodeRush.StructuralParser
Imports DevExpress.CodeRush.Core
Public Module Used
#Region "Psuedo Consts"
    Public UsableTypes() As LanguageElementType = VarAndConstDeclarationTypes
#End Region
#Region "isUnused"
    Public Function isUnused(ByVal LE As LanguageElement) As Boolean
        If LE Is Nothing Then
            Return False
        End If
        If isElementType(LE, UsableTypes) Then
            Return isUnusedVariableDeclaration(LE)
        End If
        'If isMethodDeclaration(LE) Then
        '    Return isUnusedMethod(LE)
        'End If
        Return False
    End Function
    Public Function isUnusedVariableDeclaration(ByVal LE As LanguageElement) As Boolean
        If LE Is Nothing Then
            Return False
        End If
        If SkipEvaluation(LE) Then
            Return False
        End If
        Dim References As System.Collections.ArrayList = (CType(LE, BaseVariable)).References
        Return References Is Nothing OrElse References.Count = 0
    End Function
    Private Function SkipEvaluation(ByVal LE As LanguageElement) As Boolean
        Return isDelegateParam(LE) _
               OrElse isAbstractMethod(LE.Parent) _
               OrElse isInterface(LE.Parent) _
               OrElse Not isPrivateOrLocal(CType(LE, Member)) _
               OrElse isEventHandlerParam(LE) _
               OrElse False 'isPInvokeParam(LE)
    End Function
    Private Function isEventHandlerParam(ByVal LE As LanguageElement) As Boolean
        ' Is LE a Paramater
        If Not LE.ElementType = LanguageElementType.Parameter Then
            Return False
        End If
        ' Is LE a Method
        If Not LE.Parent.ElementType = LanguageElementType.Method Then
            Return False
        End If
        Dim Method As Method = CType(LE.Parent, Method)
        Dim Param1 As Param = CType(Method.Parameters(0), Param)
        Dim FirstParamisObject As Boolean = Param1.GetTypeName.ToLower = "object"
        Dim Param2 As Param = CType(Method.Parameters(1), Param)
        Dim SecondParamEventArgs As Boolean = Param2.GetDeclaringType().DescendsFrom("System.EventArgs")
        Return FirstParamisObject AndAlso SecondParamEventArgs
    End Function
    Private Function isPInvokeParam(ByVal LE As LanguageElement) As Boolean
        Throw New NotImplementedException
    End Function
    Private Function isUnusedMethod(ByVal Method As Method) As Boolean
        If Method Is Nothing Then
            Return False
        End If
        If Method.Visibility <> MemberVisibility.Private Then
            Return False
        End If
        Return Method.FindAllReferences().Count = 0
    End Function
#End Region
End Module
